const multipart = require("koa-multer");
const path = require("path");
const fs = require("fs");
const upload = multipart({ dest: path.join(__dirname, "public/upload") });
const uploadPath = path.join(__dirname, "public/upload");
const Router = require("koa-router");
const connection = require("./mysql");
const { stringify } = require("querystring");
const router = new Router();

//已上传片段入库
const insertFile = async (md5,name,totalNumber,chunkSize,chunckNumber) => {
    const sql = `INSERT INTO fileupload.chunck_list (file_hash,chunck_number,chunck_size,chunck_total_number,file_name) VALUES ('${md5}','${chunckNumber}','${chunkSize}','${totalNumber}','${name}')`;
    const result = await connection.query(sql);
    console.log(result + '数据插入成功')
}

router.post("/upload",upload.single("file"), async (ctx, next) => {
    // const file = ctx.request.files.file; // Access the uploaded file
    const {
        totalNumber,  //分片总数
        chunckNumber, //分片序号
        chunkSize,    //分片大小
        md5,          //文件hash值（唯一）
        name
    } = ctx.req.body;
    //指定hash文件路径
    const chunckPath = path.join(uploadPath, md5,'/');
    if(!fs.existsSync(chunckPath)){
        fs.mkdirSync(chunckPath);
    }
    //移动文件到指定目录
    fs.renameSync(ctx.req.file.path,chunckPath + md5 + '-' + chunckNumber);
    //检查文件完整性
    // if(checkedChunck(totalNumber,md5)) {
    //     //处理合并文件逻辑 ...
    //     console.log('对比文件！！！！！！！！！！！！！！！！！！！！！！')
    //     mergeFile(totalNumber,md5,name);
    // }
    insertFile(md5,name,totalNumber,chunkSize,chunckNumber)
    ctx.status = 200;
    ctx.res.end('Success');
    // ctx.body = "上传成功"
})

//合并切片
router.post("/merge", async (ctx, next) => {
    const {totalNumber,md5,name} = ctx.request.body;
    try {
        //分片存储得文件夹路径
        const chunckPath = path.join(uploadPath, md5, '/');
        //创建合并后的文件
        console.log(name+'我是视频地址')
        const filePath = path.join(uploadPath, name);
        //读取对应hash文件夹下的所有分片文件名称
        const chunckList = fs.existsSync(chunckPath) ? fs.readdirSync(chunckPath) : [];
        console.log(chunckList+'我是视频地址')
        //创建储存文件
        fs.writeFileSync(filePath,'');
        //判断切片是否完整
        console.log(chunckList.length,totalNumber,'我是总地址，和分片地址')
        if(chunckList.length !== totalNumber){
            ctx.status = 500;
            ctx.message = 'Merge failed, missing file slices';
            // ctx.res.end('error');
            process.exit();
        }
        for(let i = 0; i < totalNumber; i++){
            const chunck = fs.readFileSync(chunckPath +md5+ '-' + i);
            //写入当前切片
            fs.appendFileSync(filePath,chunck);
            //删除已合并的切片 
            fs.unlinkSync(chunckPath + md5 + '-' + i);
        }
        //删除空文件夹
        fs.rmdirSync(chunckPath); 
        ctx.status = 200;
        ctx.message = 'success';
    }catch (e) {
        ctx.status = 500;
        ctx.res.end('合并失败');
    }
})

router.post("/checkChuncks", async (ctx, next) => {
    // try {
        const {md5} = ctx.request.body;
        const queryResult = await new Promise((resolve,reject)=>{
            const query = `SELECT  (SELECT count(*)  FROM chunck_list WHERE file_hash = '${md5}') as all_count, id as chunck_id,file_hash,chunck_number,chunck_total_number FROM chunck_list  WHERE file_hash = '${md5}' GROUP BY id ORDER BY chunck_number`;
            connection.query(query,async (error,results,fields)=>{
                if(error) reject(error);
                resolve(results || []);
            });  
        })
        ctx.status = 200;
        ctx.body = queryResult;
    // }catch {
    //     ctx.status = 500;
    //     ctx.body = 'select error';
    // }
})

//合并切片
const mergeFile =  (totalNumber,md5,name) => {
    console.log('开始合并文件',md5)
    var hash = md5;
    const chunckPath = path.join(uploadPath, md5, '/');
    //创建合并后的文件
    console.log(name+'我是视频地址')
    const filePath = path.join(uploadPath, name);
    //读取对应hash文件夹下的所有分片文件名称
    const chunckList = fs.existsSync(chunckPath) ? fs.readdirSync(chunckPath) : [];
    // console.log(chunckList+'我是视频地址')
    //创建储存文件
    fs.writeFileSync(filePath,'');
    //判断切片是否完整
    if(chunckList.length !== totalNumber){
        return false;
        process.exit();
    }
    for(let i = 0; i < totalNumber; i++){
        const chunck = fs.readFileSync(chunckPath +md5+ '-' + i);
        //写入当前切片
        fs.appendFileSync(filePath,chunck);
        //删除已合并的切片 
        //如果不需要秒传和断点续传可删除已合并的分片
        // fs.unlinkSync(chunckPath + md5 + '-' + i);
    }
    // //删除空文件夹
    //如果不需要秒传和断点续传可删除已合并的文件夹
    // fs.rmdirSync(chunckPath); 
    return true;
}

const SecondTransmission = async () =>{

}



//检查分片完整性
const checkedChunck = async (totalNumber,md5) => {
    const chunckPath = path.join(uploadPath, md5, '/');
    const chunckList = fs.readdirSync(chunckPath);
    console.log(totalNumber,chunckList.length,"分片序号")
    if(totalNumber === chunckList.length){
        return true;
    }else {
        return false;
    }
}

module.exports = router;


// data.append('totalNumber',fileChuncks.value.length);
// data.append("chunkSize",chunckSize.value);
// data.append("chunckNumber",i);
// data.append('md5',md5Value);
// data.append('file',new File([e.fileChuncks],fileKey))